import json
import time

import requests


class Aviation:
    def __init__(self):
        self.headers = {
            "Accept": "*/*",
            "Accept-Language": "zh-CN,zh;q=0.9",
            "Cache-Control": "no-cache",
            "Connection": "keep-alive",
            "Cookie": "9AD585D8A7CB034A=kQJSwQZO-1711416515585-56d52943b993e698171730; 1735D64331DF397E=CTE6uWOEU1^%^2FavI0VGdVkDogPfgX9hbmXFdfQgnMtpq661rvd5ANmV^%^2BOaUGyBh4PJ2gqDAn4ggD5Vg5md3U^%^2BV9A^%^3D^%^3D; _xid=2zKtjKYofTPkXflB5W9m8kJ5HQ^%^2BZqJLEyDDQJfVXj5s^%^3D^",
            "Pragma": "no-cache",
            "blackbox": "lWPSV1711419252DVprkretyh7",
            "Origin": "https://www.juneyaoair.com",
            "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/122.0.0.0 Safari/537.36",
        }
        url = "https://mediaws.juneyaoair.com/upload/flightBasicStatic/city.js"
        params = {
            "v": str(int(time.time() * 1000)),
        }
        response = requests.get(url, headers=self.headers, params=params)

        result = json.loads(response.text.split('=')[1])
        self.city_array = []
        for data in result['objData']:
            item = dict()
            item['cityName'] = data['cityName']
            item['cityCode'] = data['cityCode']
            self.city_array.append(item)

        print("数据初始化成功")

    def get_data(self, date, arr_city, dep_city):
        arr_item = list(filter(lambda obj: obj['cityName'] == arr_city, self.city_array))
        if len(arr_item) == 0:
            print(f"{arr_city}未找到城市编码")
            return
        dep_item = list(filter(lambda obj: obj['cityName'] == dep_city, self.city_array))
        if len(dep_item) == 0:
            print(f"{dep_city}未找到城市编码")
            return
        data = {
            "channelNo": "B2C",
            "data": {
                "RouteType": "OW",
                "FlightDirection": "G",
                "PassengerType": [],
                "FlightNos": "",
                "CabinClassGo": "",
                "BrandCodeGo": "",
                "SegCondList": [
                    {
                        "SegNO": 0,
                        "FlightDirection": "G",
                        "DepCity": arr_item[0]['cityCode'],
                        "ArrCity": dep_item[0]['cityCode'],
                        "FlightDate": date
                    }
                ],
                "ArrDateTimeGo": "",
                "IsTransferGo": "N"
            }
        }
        # print(data)
        url = "https://www.juneyaoair.com/api/flightFares/queryFlightSimple"
        response = requests.post(url, headers=self.headers, json=data)
        response.encoding = "utf-8"
        print(response)
        result = response.json()
        for res in result['data']['FlightInfoCombList']:
            item = dict()
            item['FlightNoComb'] = res['FlightNoComb']
            item['DepDateTime'] = res['DepDateTime']
            item['DepAirportName'] = res['DepAirportName'] + res['DepTerm']
            item['ArrDateTime'] = res['ArrDateTime']
            item['ArrAirportName'] = res['ArrAirportName'] + res['ArrTerm']
            item['cabin'] = []
            for cabin in res['CabinFareCombList']:
                price = 0
                y_price = 0
                if 'CabinFareSeparateList' in cabin:
                    for p in cabin['CabinFareSeparateList']:
                        y_price += float(p['YPrice'])
                        price += float(p['PriceValue'])
                else:
                    price = cabin['PriceValue']
                    y_price = cabin['PriceValue']

                item['cabin'].append([cabin['BrandName'], price, y_price])
            print(item)


if __name__ == '__main__':
    a = Aviation()
    date = input("输入查询日期(YYYY-MM-DD): ")
    arr_city = input("输入出发地: ")
    dep_city = input("输入目的地: ")
    a.get_data(date, arr_city, dep_city)
